/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Almcenar.java
 *
 * Created on 01-oct-2012, 19:58:11
 */
package gestordatos;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
//import sun.org.mozilla.javascript.internal.regexp.SubString;

/**
 *
 * @author cusco
 */
  
public class Almcenar extends javax.swing.JFrame {
  
 private String cadena;
    DefaultTableModel tabla=new DefaultTableModel();
    DefaultTableModel tabla1=new DefaultTableModel();
    private String cadena1;
    //
     String TipoRegistro="";
    String TipoArchivo="";
    String ConfLongitudVariable="";
    String ConfLongitudFija="";
    String TipoBorrado="";
     String[] tamaño;
    /** Creates new form Almcenar */
    public Almcenar() {
        initComponents();
        String Titulos[]={"Campo","Tipo","Longitud","PK"};
        tabla.setColumnIdentifiers(Titulos);
        this.jTabla.setModel(tabla);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        buttonGroup3 = new javax.swing.ButtonGroup();
        buttonGroup4 = new javax.swing.ButtonGroup();
        buttonGroup5 = new javax.swing.ButtonGroup();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanelDefinicion = new javax.swing.JPanel();
        jtxtCampo = new javax.swing.JTextField();
        jtxtLongitud = new javax.swing.JTextField();
        jcbxTipo = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTabla = new javax.swing.JTable();
        jtbnEliminar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jbtnGuardar = new javax.swing.JButton();
        jcbxPK = new javax.swing.JComboBox();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTableDatos = new javax.swing.JTable();
        jbtnAbrirEstructura = new javax.swing.JButton();
        jbtnNuevaFila = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jtxtCampo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtxtCampoActionPerformed(evt);
            }
        });

        jcbxTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Entero", "Real", "Fecha", "Char", "Varchar" }));

        jButton1.setText("Agregar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Campo", "Tipo", "Longitud", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTabla);

        jtbnEliminar.setText("Eliminar Campo");
        jtbnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtbnEliminarActionPerformed(evt);
            }
        });

        jLabel1.setText("Nombre de Campo");

        jLabel2.setText("Tipo de Datos");

        jLabel3.setText("Longitud");

        jbtnGuardar.setText("Guardar Estructura");
        jbtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGuardarActionPerformed(evt);
            }
        });

        jcbxPK.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Si", "No" }));

        jTableDatos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane4.setViewportView(jTableDatos);

        jbtnAbrirEstructura.setText("Abrir Estructura");
        jbtnAbrirEstructura.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAbrirEstructuraActionPerformed(evt);
            }
        });

        jbtnNuevaFila.setText("Nuevo");
        jbtnNuevaFila.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNuevaFilaActionPerformed(evt);
            }
        });

        jButton2.setText("Convertir a Bytes");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelDefinicionLayout = new javax.swing.GroupLayout(jPanelDefinicion);
        jPanelDefinicion.setLayout(jPanelDefinicionLayout);
        jPanelDefinicionLayout.setHorizontalGroup(
            jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelDefinicionLayout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelDefinicionLayout.createSequentialGroup()
                        .addGroup(jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jtxtCampo, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(43, 43, 43)
                        .addGroup(jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jcbxTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(55, 55, 55)
                        .addGroup(jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanelDefinicionLayout.createSequentialGroup()
                                .addComponent(jtxtLongitud, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(42, 42, 42)
                                .addComponent(jcbxPK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel3)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 515, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                .addGroup(jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnGuardar)
                    .addComponent(jtbnEliminar))
                .addGap(48, 48, 48))
            .addGroup(jPanelDefinicionLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(40, 40, 40)
                .addGroup(jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnAbrirEstructura)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(117, Short.MAX_VALUE))
            .addGroup(jPanelDefinicionLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jbtnNuevaFila)
                .addContainerGap(678, Short.MAX_VALUE))
        );
        jPanelDefinicionLayout.setVerticalGroup(
            jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelDefinicionLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addGap(13, 13, 13)
                .addGroup(jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtCampo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jcbxTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtLongitud, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jcbxPK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(29, 29, 29)
                .addGroup(jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanelDefinicionLayout.createSequentialGroup()
                        .addComponent(jbtnGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jtbnEliminar)))
                .addGap(81, 81, 81)
                .addComponent(jbtnNuevaFila)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelDefinicionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanelDefinicionLayout.createSequentialGroup()
                        .addComponent(jbtnAbrirEstructura)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)))
                .addContainerGap(81, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Definicion de Tabla", jPanelDefinicion);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 756, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtnNuevaFilaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNuevaFilaActionPerformed
        tabla1=(DefaultTableModel) jTableDatos.getModel();
        String filavacia[]=new String[3];
        tabla1.addRow(filavacia);///*****
}//GEN-LAST:event_jbtnNuevaFilaActionPerformed

    private void jbtnAbrirEstructuraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAbrirEstructuraActionPerformed
        File file = new File("");
        JFileChooser selector = new JFileChooser();
        selector.setDialogTitle("Abrir archivo");
        selector.setDialogType(JFileChooser.OPEN_DIALOG);
        int resultado = selector.showOpenDialog(null);
        if(resultado == JFileChooser.APPROVE_OPTION) {
            file = selector.getSelectedFile();
        }
        
        cadena=file.getAbsolutePath();
        
        File f;
        FileReader lectorArchivo;
        //String[] cm=null;
        try{
            f=new File(cadena);
            lectorArchivo =new FileReader(f);
            BufferedReader br=new BufferedReader(lectorArchivo);
            String linea=br.readLine();
            String cm="";
            String n="";
            int i=0;
            
           
            while (linea !=null){
                String[] arr= linea.split(" ");
                String campos=arr[0];
                String v=arr[1];
                String c=arr[2];
                cm=cm +campos+":";
                n=n +c+":";
                i=i+1;
                System.out.println(campos);
                linea=br.readLine();
            }
            //String cmm="fff:hhh:kkk";
            
            String[] p=cm.split(":");
             tamaño=n.split(":"); 
            //this.jatxtmetadatos.setText(p[2]);
            int l= p.length;
            //
            //          String[] titu;
            //          for(int k=0;k<=l;k++){
            //              titu[k]=p[k];
            //          }
            //          //
              //String Titulos[]={p[0],p[1],p[2],p[3]};
           // for(int y=0;y<l;y++)
            //{
             
               tabla1.setColumnIdentifiers(p);
               this.jTableDatos.setModel(tabla1);
               br.close();
            //}
        }catch (IOException e){
            System.out.println("Error:"+e.getMessage());
        }
        //        initComponents();
        //        String Titulos[]={p[0],p[1],p[2]};
        //        tabla.setColumnIdentifiers(Titulos);
        //        this.jTableDatos.setModel(tabla);
        
        
        
        
        
        
        
    }//GEN-LAST:event_jbtnAbrirEstructuraActionPerformed

    private void jbtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGuardarActionPerformed
        File file = new File("");
        JFileChooser selector = new JFileChooser();
        selector.setDialogTitle("Guardar archivo");
        selector.setDialogType(JFileChooser.OPEN_DIALOG);
        int resultado = selector.showOpenDialog(null);
        if(resultado == JFileChooser.APPROVE_OPTION) {
            file = selector.getSelectedFile();
        }
        
        cadena=file.getAbsolutePath();
        //*****************
        String datos;
        int n= tabla.getRowCount();
        // datos =this.jTabla.getValueAt(0,0).toString()+" "+this.jTabla.getValueAt(0,1).toString()
        //        +" "+this.jTabla.getValueAt(0,2).toString()+" "+this.jTabla.getValueAt(0,3).toString();
        FileWriter fichero = null;
        PrintWriter pw = null;
        try {
            fichero = new FileWriter(cadena);
            pw = new PrintWriter(fichero);
            
            for (int i = 0; i < n; i++){
                datos =this.jTabla.getValueAt(i,0).toString()+"    "+this.jTabla.getValueAt(i,1).toString()
                        +"    "+this.jTabla.getValueAt(i,2).toString()+"    "+this.jTabla.getValueAt(i,3).toString();
                pw.println(datos);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Nuevamente aprovechamos el finally para
                // asegurarnos que se cierra el fichero.
                if (null != fichero)
                    fichero.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        
        //-------------------------
    /*int n;
    n= tabla.getRowCount();
    String datos;
    CArchivo a=new CArchivo();
    a.crearArchivo();
    a.escribirArchivo();
    a.leerArchivo();*/
        
        //*******************************************
        //datos =this.jTabla.getValueAt(1,1).toString();
        //jTextField1.setText(datos);
}//GEN-LAST:event_jbtnGuardarActionPerformed

    private void jtbnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtbnEliminarActionPerformed
        int fila,n;
        fila= this.jTabla.getSelectedRow();
        if(fila>=0){
            tabla.removeRow(fila);
        } else{
            JOptionPane.showMessageDialog(null, "no selecciono ninguna  fila");
        }
}//GEN-LAST:event_jtbnEliminarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        int n;
        String datos[]=new String[4];
        datos[0]=this.jtxtCampo.getText();
        this.jtxtCampo.setText(null);
        datos[1]=this.jcbxTipo.getSelectedItem().toString();
        datos[2]=this.jtxtLongitud.getText();
        this.jtxtLongitud.setText(null);
        datos[3]=this.jcbxPK.getSelectedItem().toString();
        tabla.addRow(datos);
        this.jtxtCampo.grabFocus();
        n= tabla.getRowCount();
        //this.jt
        
        
        
    /*archivo a= new archivo();
    String campo= this.jtxtCampo.getText()+" "+this.jcbxTipo.getSelectedItem()+" "+this.jtxtLongitud.getText();
     
    a.concatenar("archivo.txt",campo+'\n');
    System.out.println(a.leer("archivo.txt"));*/
}//GEN-LAST:event_jButton1ActionPerformed

    private void jtxtCampoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtxtCampoActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_jtxtCampoActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        FileOutputStream out = null;
        try {
            File file = new File("");
            JFileChooser selector = new JFileChooser();
            selector.setDialogTitle("Guardar archivo");
            selector.setDialogType(JFileChooser.OPEN_DIALOG);
            int resultado = selector.showOpenDialog(null);
            if(resultado == JFileChooser.APPROVE_OPTION) {
                file = selector.getSelectedFile();
            }
            String datos;
                    
        FileWriter fichero = null;
        PrintWriter pw = null;
            cadena=file.getAbsolutePath();
            out = new FileOutputStream(cadena);
            for(int i=0;i<jTableDatos.getRowCount();i++)
            {
                for(int y=0;y<jTableDatos.getColumnCount();y++)
                {
                    //FileOutputStream fileOutput = null;
            
                       // byte[] Dato=;
                     try
                     {
                       
                         JOptionPane.showMessageDialog(null,jTableDatos.getValueAt(i, y).toString().getBytes(),"Aviso",JOptionPane.PLAIN_MESSAGE);
                        out.write(jTableDatos.getValueAt(i, y).toString().getBytes());
                        
                        
                     }
                     catch(IOException e){
                System.out.println("Error:"+e.getMessage());
                       
            }
            }
                
            }
            try {
                out.flush();
                out.close();
                
                // TODO add your handling code here:
            } catch (IOException ex) {
                Logger.getLogger(Almcenar.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Almcenar.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                Logger.getLogger(Almcenar.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Almcenar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Almcenar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Almcenar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Almcenar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Almcenar().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.ButtonGroup buttonGroup3;
    private javax.swing.ButtonGroup buttonGroup4;
    private javax.swing.ButtonGroup buttonGroup5;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanelDefinicion;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTabla;
    private javax.swing.JTable jTableDatos;
    private javax.swing.JButton jbtnAbrirEstructura;
    private javax.swing.JButton jbtnGuardar;
    private javax.swing.JButton jbtnNuevaFila;
    private javax.swing.JComboBox jcbxPK;
    private javax.swing.JComboBox jcbxTipo;
    private javax.swing.JButton jtbnEliminar;
    private javax.swing.JTextField jtxtCampo;
    private javax.swing.JTextField jtxtLongitud;
    // End of variables declaration//GEN-END:variables
}
